package com.zerui.manager.accessauthpersonnel.domainservice;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zerui.manager.accessauthdevice.domainservice.AccessAuthDeviceRepository;
import com.zerui.manager.accessauthpersonnel.AccessAuthPersonnel;
import com.zerui.manager.accessauthpersonnel.gateway.AccessAuthPersonnelGateWay;
import com.zerui.manager.web.cmd.AccessAuthPersonnelBindCmd;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author wh
 * @create_time 2023-08-23 11:07
 */
@Component
public class AccessAuthPersonnelRepository {

	@Resource
	private AccessAuthPersonnelGateWay accessAuthPersonnelGateWay;
    @Resource
	private AccessAuthDeviceRepository accessAuthDeviceRepository;

    public List<AccessAuthPersonnel> getByPersonnelIds(List<Long> personnelIds) {
        return accessAuthPersonnelGateWay.getByPersonnelIds(personnelIds);
    }

    public void addBatch(List<AccessAuthPersonnel> accessAuthPersonals) {
        accessAuthPersonnelGateWay.addBatch(accessAuthPersonals);
    }

    public List<Long> deleteBatch(AccessAuthPersonnelBindCmd cmd) {
        return accessAuthPersonnelGateWay.deleteBatch(cmd);
    }

    public void deleteByPersonIds(List<Long> ids) {
        List<AccessAuthPersonnel> accessAuthPersonnel =  accessAuthPersonnelGateWay.getByPersonnelIds(ids);
        if(CollectionUtils.isEmpty(accessAuthPersonnel)){
            return;
        }
        List<Long> accessAuthPersonIds = accessAuthPersonnel.stream().map(AccessAuthPersonnel::getId).collect(Collectors.toList());
        accessAuthPersonnelGateWay.deleteByIds(accessAuthPersonIds);
        Map<Long, List<AccessAuthPersonnel>> map = accessAuthPersonnel.stream().collect(Collectors.groupingBy(AccessAuthPersonnel::getAccessAuthId));
        map.forEach((key,val)->{
	        List<Long> personList = val.stream()
                    .map(AccessAuthPersonnel::getPersonnelId)
                    .collect(Collectors.toList());

            accessAuthDeviceRepository.devicesDeleteDistributePermissionsByPersonals(key, personList);
        });
    }
}
